import { useEffect, useMemo, useState } from 'react'
import PageComponent from '@components/pageComponent'
import { getDetailRequest, getCourtRequest, updateArbitratorRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import PageLoading from '@components/pageLoading'
import PageEmpty from '@components/pageEmpty'
import { Result, Form, Button, Toast, Dialog } from 'antd-mobile'
import style from './index.module.less'
import ArbitratorPicker from '@components/arbitratorPicker'
import { pop } from '@src/redux/reducers/pages'
import _ from 'lodash'
import { refreshArbitratorVersion } from '@src/redux/reducers/cases'

const { useForm, Item } = Form

async function initCaseDetail (caseid, setData, setError) {
  const [e, d] = await awaitWrap(getDetailRequest(caseid))
  if (e !== null) {
    setError(true)
  }
  if (e === null && d !== null) {
    setData(d)
  }
}

async function initCourtItems (caseDetail, uid, setList, setError) {
  const [e, d] = await awaitWrap(getCourtRequest(caseDetail.id, caseDetail, uid))
  if (e !== null) {
    setError(true)
  }
  if (e === null && d !== null) {
    setList(d)
  }
}

// 初始化当事人的仲裁员选择情况
function initData (list, id, setData) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === id) {
      setData(list[i])
      break
    }
  }
}

function initDay (d, o, setDay) {
  const list = [...d.applicants, ...d.respondents]
  const day = d.procedure === '简易程序' ? 5 : 10
  const id = o.partyid
  for (let i = 0; i < list.length; i++) {
    const o = list[i]
    if (o.id === id && ['港', '台', '澳', '国外', '外国', '港澳台'].includes(o.area)) {
      return setDay(day * 2)
    }
  }
  setDay(day)
}

async function submitHandle (d, party, dispatch) {
  const o = formatSubmitData(d, party)
  if (o.arbitratorid !== undefined && o.arbitratorid !== null && o.arbitratorid === o.arbitratorid1) {
    Toast.show({ content: '两个仲裁员不能相同' })
    return undefined
  }
  Toast.show({ content: '提交中', duration: 0, icon: 'loading' })
  const [e] = await awaitWrap(updateArbitratorRequest(o))
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    dispatch(pop())
    dispatch(refreshArbitratorVersion())
  }
}

function formatSubmitData (d, party) {
  const isThree = party.tribunal_type === '三人庭'
  const o = _.cloneDeep(party)
  if (d.arbitrator !== undefined) {
    if (d.arbitrator.id !== undefined && d.arbitrator.name !== undefined && d.arbitrator.id !== null && d.arbitrator.name !== null) {
      o.arbitrator = d.arbitrator.name
      o.arbitratorid = d.arbitrator.id
      if (o.arbitrator_sel_status !== '完成') {
        o.arbitrator_sel_datetime = Math.floor(Date.now() / 1000)
      }
    }
  }
  if (d.arbitrator1 !== undefined && isThree) {
    if (d.arbitrator1.id !== undefined && d.arbitrator1.name !== undefined && d.arbitrator1.id !== null && d.arbitrator1.name !== null) {
      o.arbitrator1 = d.arbitrator1.name
      o.arbitratorid1 = d.arbitrator1.id
      if (o.arbitrator1_sel_status !== '完成') {
        o.arbitrator1_sel_datetime = Math.floor(Date.now() / 1000)
      }
    }
  }
  return o
}

function Main ({ meta }) {
  const [formRef] = useForm()
  const dispatch = useAppDispatch()
  const userInfo = useAppSelector(state => state.basic.userInfo)
  const [caseDetail, setCaseDetail] = useState(null)
  const [courtItems, setCourtItems] = useState([])
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)
  const [error, setError] = useState(false)
  const [day, setDay] = useState(0)
  const caseid = useMemo(() => {
    return meta && meta.caseid ? meta.caseid : ''
  }, [meta])
  const id = useMemo(() => {
    return meta && meta.id ? meta.id : ''
  }, [meta])
  useEffect(() => {
    if (caseid) {
      initCaseDetail(caseid, setCaseDetail, setError)
    }
  }, [caseid])
  useEffect(() => {
    if (caseDetail) {
      initCourtItems(caseDetail, userInfo.id, setCourtItems, setError)
    }
  }, [caseDetail, userInfo])
  useEffect(() => {
    if (courtItems.length) {
      initData(courtItems, id, setData)
      setLoading(false)
    }
  }, [courtItems, id])
  useEffect(() => {
    if (caseDetail && data) {
      initDay(caseDetail, data, setDay)
    }
  }, [caseDetail, data])
  if (error) {
    return (
      <PageComponent title='录入仲裁员'>
        <Result
          status='error'
          title='加载数据失败'
        />
      </PageComponent>
    )
  }
  if (loading) {
    return (
      <PageComponent title='录入仲裁员'>
        <PageLoading />
      </PageComponent>
    )
  }
  if (!data) {
    return (
      <PageComponent title='录入仲裁员'>
        <PageEmpty />
      </PageComponent>
    )
  }
  return (
    <PageComponent title='录入仲裁员'>
      <div className={style.container}>
        <div className={style.notice}>请在收到通知之日起{day}日内选定仲裁员，选定是否有效以秘书最终确认为准</div>
        <Form form={formRef} layout='horizontal' onFinish={d => {
          Dialog.confirm({
            content: '您确定要提交吗？',
            onConfirm: () => {
              submitHandle(d, data, dispatch)
            }
          })
        }}>
          <ArbitratorPicker label={`${data.tribunal_type === '三人庭' ? '首席' : ''}仲裁员`} name='arbitrator' rules={[{ required: true, message: '仲裁员不能为空' }]} disabled={data.arbitrator_sel_status === '完成'} />
          {
            data.tribunal_type === '三人庭'
              ? (
                <ArbitratorPicker label='仲裁员' name='arbitrator1' rules={[{ required: true, message: '仲裁员不能为空' }]} disabled={data.arbitrator1_sel_status === '完成'} />
                )
              : null
          }
          <Item>
            <Button color='primary' type='submit' block>提交</Button>
          </Item>
        </Form>
      </div>
    </PageComponent>
  )
}

export default Main
